# -*- coding: utf-8 -*-

import os
import sys
from contextlib import closing
import time
import datetime
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random, hashlib
import StringIO
import httplib
import urllib
import simplejson
import jinja2
import werkzeug.utils
import openerp, logging
from openerp import http
from openerp.http import request
from openerp.addons.wechat.official import WxApi, WxApplication
from openerp.report.render.rml2pdf import customfonts
logger = logging.getLogger(__name__)
from openerp.http import STATIC_CACHE
# wifidog ping
if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_weixin', "html")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True)

SUPERUSER_ID = 1




#########################################################################
# 建立验证码图片
#########################################################################
_letter_cases = "abcdefghjkmnpqrstuvwxy" # 小写字母，去除不好的字符
_upper_cases = _letter_cases.upper() # 大写字母
_numbers = ''.join(map(str, range(2, 10))) # 数字
_init_chars = ''.join((_letter_cases, _upper_cases, _numbers))
fonts_list = customfonts.list_all_sysfonts()
font_file = fonts_list[1]
def create_validate_code(size=(100, 40),
                         chars=_numbers,
                         img_type="GIF",
                         mode="RGB",
                         bg_color=(255, 255, 255),
                         fg_color=(0, 0, 255),
                         font_size=23,
                         length=4,
                         draw_lines=True,
                         n_line=(1, 2),
                         draw_points=True,
                         point_chance = 2):
    '''
    @todo: 生成验证码图片
    @param size: 图片的大小，格式（宽，高），默认为(120, 30)
    @param chars: 允许的字符集合，格式字符串
    @param img_type: 图片保存的格式，默认为GIF，可选的为GIF，JPEG，TIFF，PNG
    @param mode: 图片模式，默认为RGB
    @param bg_color: 背景颜色，默认为白色
    @param fg_color: 前景色，验证码字符颜色，默认为蓝色#0000FF
    @param font_size: 验证码字体大小
    @param font_type: 验证码字体，默认为 ae_AlArabiya.ttf
    @param length: 验证码字符个数
    @param draw_lines: 是否划干扰线
    @param n_lines: 干扰线的条数范围，格式元组，默认为(1, 2)，只有draw_lines为True时有效
    @param draw_points: 是否画干扰点
    @param point_chance: 干扰点出现的概率，大小范围[0, 100]
    @return: [0]: PIL Image实例
    @return: [1]: 验证码图片中的字符串
    '''
    width, height = size
    img = Image.new(mode, size, bg_color) # 创建图形
    draw = ImageDraw.Draw(img) # 创建画笔
    def get_chars():
        '''生成给定长度的字符串，返回列表格式'''
        return random.sample(chars, length)
    def create_lines():
        '''绘制干扰线'''
        line_num = random.randint(*n_line) # 干扰线条数
        for i in range(line_num):
            # 起始点
            begin = (random.randint(0, size[0]), random.randint(0, size[1]))
            #结束点
            end = (random.randint(0, size[0]), random.randint(0, size[1]))
            draw.line([begin, end], fill=(0, 0, 0))
    def create_points():
        '''绘制干扰点'''
        chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100]

        for w in xrange(width):
            for h in xrange(height):
                tmp = random.randint(0, 100)
                if tmp > 100 - chance:
                    draw.point((w, h), fill=(0, 0, 0))
    def create_strs():
        '''绘制验证码字符'''
        c_chars = get_chars()
        strs = ' %s ' % ' '.join(c_chars) # 每个字符前后以空格隔开

        font = ImageFont.truetype(font_file, font_size)
        font_width, font_height = font.getsize(strs)
        draw.text(((width - font_width) / 2.6, (height - font_height) / 2),
                    strs, font=font, fill=fg_color)

        return ''.join(c_chars)
    if draw_lines:
        create_lines()
    if draw_points:
        create_points()
    strs = create_strs()
    # 图形扭曲参数
    params = (1 - float(random.randint(1, 2)) / 100,
              0,
              0,
              0,
              1 - float(random.randint(1, 10)) / 100,
              float(random.randint(1, 2)) / 500,
              0.001,
              float(random.randint(1, 2)) / 500
    )
    #img = img.transform(size, Image.PERSPECTIVE, params) # 创建扭曲
    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜，边界加强（阈值更大）
    return img, strs



class WxOfficialTest(WxApplication):
    is_initialized = False
    wxapi = None

    def __init__(self):
        if self.is_initialized:
            return
        self.is_initialized = True
        # 取得微信应用配置
        self.TOKEN = 'aaa'
        self.ENCODING_AES_KEY = ''
        self.APP_ID = 'wx5339704d49fe9c83'
        self.SECRET = '76b49a44cef630c668006cf57e41b27b'
        self.wxapi = WxApi(self.APP_ID, self.SECRET)


class weixin_official_test(http.Controller):
    weixin_app = None

    def __init__(self):
        # env.globals['_pool'] = ModelPool()
        # env.globals['_cr'] = CursorProxy()
        # env.globals['_page'] = PageProxy()
        # env.globals['_slug'] = _slug
        # env.globals.update(common_functions)
        # env.filters['tojson'] = simplejson.dumps
        self.weixin_app = WxOfficialTest()

    # 微信服务号回调入口网址
    @http.route('/weixin/official', auth='public')
    def weixin(self, **kw):
        result = self.weixin_app.process(request.httprequest.args, request.httprequest.data)
        return result


    @http.route('weixin/card/exchange/index', auth='public', website=True)
    def card_exchange_index(self, **kw):
        registry, cr, uid, context = request.registry, request.cr, request.session.uid, request.context
        #是否微信查询
        chaxun = kw.get('chaxun')
        #记录刷新页面时的时间
        http.request.session.open_time = time.time()
        #session中取得openid，如果有的话
        openid = http.request.session.openid
        #查询此openid的兑换记录
        apply_delivery = registry.get('apply.delivery')
        values = {'chaxun': chaxun, 'openid': openid, 'exchange_prompt': registry.get('ir.config_parameter')\
                                                .get_param(cr, uid, 'exchange_prompt')}
        if openid:
            exchange_ids = apply_delivery.search(cr, SUPERUSER_ID, [('openid', '=', openid)])
            values['exchanges'] = apply_delivery.browse(cr, SUPERUSER_ID, exchange_ids)

        return http.request.website.render('dftg_weixin.index', values)

    @http.route(['/card/exchange/<int:partner_id>/',
                 '/card/exchange/index'], auth='public', website=True)
    def card_exchange_index(self, partner_id=False, **kw):
        registry, cr, uid, context = request.registry, request.cr, request.session.uid, request.context
        #是否微信查询
        chaxun = kw.get('chaxun')
        #记录刷新页面时的时间
        http.request.session.open_time = time.time()
        #session中取得openid，如果有的话
        openid = http.request.session.openid
        #查询此openid的兑换记录
        apply_delivery = registry.get('apply.delivery')
        partner_obj = registry.get('res.partner')
        values = {'chaxun': chaxun, 'openid': openid, 'exchange_prompt': registry.get('ir.config_parameter')\
                                                .get_param(cr, uid, 'exchange_prompt')}
        if openid:
            exchange_ids = apply_delivery.search(cr, SUPERUSER_ID, [('openid', '=', openid)])
            values['exchanges'] = apply_delivery.browse(cr, SUPERUSER_ID, exchange_ids)
        if partner_id:
            partner = partner_obj.browse(cr, SUPERUSER_ID, partner_id, context=context)
            values.update({'partner': partner})
        else:
            values.update({'partner': False})
        return http.request.website.render('dftg_weixin.index', values)
        # template = env.get_template("card/index.html")
        # return template.render(values)

    @http.route('/card/exchange/verify', auth='public', website=True)
    def card_exchange_verify(self, card_code, card_password, validate_code, partner_id=False):
        cr, uid, context = http.request.cr, http.request.uid, http.request.context
        #检查验证码
        session_validate_code = http.request.session.validate_code
        if session_validate_code:
            session_validate_code = session_validate_code.lower()
        if not validate_code or session_validate_code != validate_code.lower():
            kw = {'validate_code_error': 1}
            return werkzeug.utils.redirect('/card/exchange/index' + '?' + urllib.urlencode(kw))

        #检查卡券密码
        cr.execute('SELECT id, is_active, is_enabled, is_exchanged FROM product_card_line WHERE code=%s'
                   , (card_code,))
        card = cr.dictfetchone()
        if card:
            cr.execute("SELECT * FROM product_card_password WHERE line_id=%s", (card['id'],))
            password = cr.dictfetchone()['password']
            if card_password != password:
                card = None

        if not card:
            kw = {'code_or_password_error': 1}
            return werkzeug.utils.redirect('/card/exchange/index' + '?' + urllib.urlencode(kw))

        if not card['is_active']:
            kw = {'is_active_error': 1}
            return werkzeug.utils.redirect('/card/exchange/index' + '?' + urllib.urlencode(kw))

        if not card['is_enabled']:
            kw = {'is_enabled_error': 1}
            return werkzeug.utils.redirect('/card/exchange/index' + '?' + urllib.urlencode(kw))

        #放入session中
        request.session.card_code = card_code
        if card['is_exchanged']:
            return werkzeug.utils.redirect('/card/exchange/info/%s' % partner_id if partner_id else '/card/exchange/info')
        else:
            return werkzeug.utils.redirect('/card/exchange/new/%s' % partner_id if partner_id else '/card/exchange/new')

    #验证码校验
    @http.route('/card/exchange/validate_code_verify', auth='public', website=True)
    def card_exchange_validate_code_verify(self, validate_code):
        #检查验证码
        session_validate_code = http.request.session.validate_code
        if session_validate_code:
            session_validate_code = session_validate_code.lower()
        if not validate_code or session_validate_code != validate_code.lower():
            return 'false'
        return 'true'

    #卡券兑换新增
    @staticmethod
    def card_exchange_save(args):
        registry, cr, uid, context = request.registry, request.cr, request.session.uid, request.context
        result = 0
        #从session中取得卡号
        card_code = request.session.card_code
        #从session中取得openid
        openid = request.session.openid
        cr.execute("SELECT id, is_active, is_enabled, is_exchanged, product_id, so_id FROM product_card_line WHERE code=%s", (card_code,))
        card = cr.dictfetchone()
        card_so_id = card['so_id']
        cr.execute('SELECT partner_id FROM sale_order WHERE id=%s', (card_so_id,))
        sale_order = cr.dictfetchone()
        partner_id = sale_order['partner_id']
        #如果卡券编号存在且已激活且已启用且没有兑换
        if card and card['is_active'] and card['is_enabled'] and not card['is_exchanged']:
            #取得密码
            cr.execute("SELECT password FROM product_card_password WHERE line_id=%s" % (card['id'],))
            password = cr.dictfetchone()['password']
            product_card_track = registry.get('product.card.track')
            apply_delivery = registry.get('apply.delivery')
            #建立兑换记录
            #apply_delivery.create时会自动建立track记录
            suite = args.get('suite')
            values = {
                'code': card['id'],
                'copy_code': card_code,
                'password': password,
                'partner_id': partner_id, #对应的卡券订单的客户
                'card_so_id': card_so_id, #对应的卡券订单(很重要, 没有的话会导致修改提货记录套装选项后无法重建提货订单)
                'is_multiple_choice_one': args.get('is_multiple_choice_one'),
                'province_id': args.get('province'),
                'city_id': args.get('city'),
                'county_id': args.get('county'),
                'address': args.get('address'),
                'postal_code': args.get('postal_code'),
                'to_name': args.get('to_name'),
                'ship_memo': args.get('ship_memo'),
                'mobile_number': args.get('mobile_number'),
                'phone_number': args.get('phone_number'),
                'estimated_ship_date': args.get('delivery_date'),
                'openid': openid,
                'suite': 1
            }
            if suite:
                values['suite'] = int(suite)
            result = apply_delivery.create(cr, SUPERUSER_ID, values, context=context)

        #返回兑换记录主键
        return result

    @http.route(['/card/exchange/new',
                 '/card/exchange/new/<int:partner_id>',
                 ], auth='public', website=True)
    def card_exchange_new(self, partner_id=False, **kw):
        registry, cr, uid, context = request.registry, request.cr, request.session.uid, request.context
        values = kw
        message = []
        partner_obj = registry.get("res.partner")
        partner = False
        if partner_id or values.get('partner_id'):
            partner_id = partner_id or values.get('partner_id')
            partner = partner_obj.browse(cr, SUPERUSER_ID, partner_id, context=context)
        #起始发货日期
        config_start_delivery_date_string = registry.get('ir.config_parameter')\
                                                .get_param(cr, uid, 'estimated_ship_start_date') or '2015-09-01'
        #结束发货日期
        config_end_delivery_date_string = registry.get('ir.config_parameter')\
                                                .get_param(cr, uid, 'estimated_ship_end_date') or '2016-02-01'

        config_start_delivery_date = datetime.datetime.strptime(config_start_delivery_date_string +\
                                                                ' 00:00:00', '%Y-%m-%d %H:%M:%S')
        #config_start_delivery_date = config_start_delivery_date.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))

        config_end_delivery_date = datetime.datetime.strptime(config_end_delivery_date_string +\
                                                              ' 23:59:59', '%Y-%m-%d %H:%M:%S')
        #config_end_delivery_date = config_end_delivery_date.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))

        now = datetime.datetime.now()
        #默认预计发货日期为第二天
        start_delivery_date = now + datetime.timedelta(hours=8) + datetime.timedelta(days=1)
        #start_delivery_date = start_delivery_date.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))
        start_delivery_date = datetime.datetime(start_delivery_date.year, start_delivery_date.month, start_delivery_date.day, 00, 00, 00)
        if config_start_delivery_date > start_delivery_date:
            start_delivery_date = config_start_delivery_date

        #如果提交了兑换请求
        if kw.get('submit') == 'exchange':
            #检查提交内容
            if kw.get('is_multiple_choice_one') and not values.get('suite'):
                message.append(u'请选择提货的产品')
            if not values.get('to_name'):
                message.append(u'请输入收货人姓名')
            if not values.get('mobile_number') and not values.get('phone_number'):
                message.append(u'请填写手机号码或者电话号码至少一个')
            if not values.get('delivery_date'):
                message.append(u'请选择期望发货日期')
            if not values.get('province'):
                message.append(u'请选择省市')
            if not values.get('city'):
                message.append(u'请选择市')
            if not values.get('county'):
                message.append(u'请选县区')
            if not values.get('address'):
                message.append(u'请输入街道门牌地址')
            else:
                try:
                    input_delivery_date = datetime.datetime.strptime(values.get('delivery_date') +\
                                                                ' 07:07:07', '%Y-%m-%d %H:%M:%S')
                    #input_delivery_date = input_delivery_date.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))
                    #如果早于允许的起始选择时间，则提示错误
                    if input_delivery_date < start_delivery_date:
                        message.append(u'选择的期望发货日期不能早于' + start_delivery_date.strftime('%Y-%m-%d'))
                    if input_delivery_date > config_end_delivery_date:
                        message.append(u'选择的期望发货日期不能晚于' + config_end_delivery_date_string)
                except ValueError as ve:
                    message.append(u'日期格式不正确, 需要减号隔开年月日，如: 2016-01-01')

            if not message:
                if kw.get('is_multiple_choice_one'):
                    kw['is_multiple_choice_one'] = True
                result = weixin_official_test.card_exchange_save(kw)

                if result:
                    base_url = '/card/exchange/info/%s' % partner_id if partner_id else '/card/exchange/info'
                    return werkzeug.utils.redirect(base_url + '?exchange_ok=1')
                else:
                    message.append(u'卡券提货记录保存失败，请联系客服')

        #从session中取得卡号
        card_code = request.session.card_code

        #取得卡券对应的卡券定义
        cr.execute('SELECT id, is_active, is_enabled, is_exchanged, so_id FROM product_card_line WHERE code=%s',
                   (card_code,))
        card = cr.dictfetchone()
        if card:
            so_id = card['so_id']

            # 取得销售订单
            cr.execute("SELECT is_multiple_choice_one, note, origin FROM sale_order WHERE id=%s", (so_id,))
            sale_order = cr.dictfetchone()

            get_provinces_sql = "SELECT rcs.id, rcs.name FROM res_country_state rcs " \
            "INNER JOIN res_country rc ON rc.id=rcs.country_id " \
            "WHERE rc.name=%s"
            sql_where = ('China',)

            origin_provinces = sale_order.get('origin')
            if origin_provinces:
                if origin_provinces.find(',') > 0 or origin_provinces.find('，') > 0:
                    get_provinces_sql += u" AND rcs.name IN %s"
                    origin_provinces = tuple(origin_provinces.replace('，', ',').replace(' ', '').split(','))
                    sql_where += (origin_provinces,)
                else:
                    get_provinces_sql += u" AND rcs.name LIKE %s"
                    sql_where += ('%' + sale_order.get('origin') + '%',)
            #取得省份列表
            cr.execute(get_provinces_sql, sql_where)
            provinces = cr.dictfetchall()
            #省份列表按中文读音排序
            provinces_sorted = provinces

            #如果有选择省份，则取得城市列表
            values['cities'] = []
            if kw.get('province'):
                cr.execute('SELECT id, city_name as name FROM all_city WHERE province_id=%s', (kw.get('province'),))
                values['cities'] = cr.dictfetchall()
                values['cities'] = values['cities']
            #如果有选择城市，则取得市县列表
            values['counties'] = []
            if kw.get('city'):
                cr.execute('SELECT id, county_name as name FROM all_county WHERE city_id=%s', (kw.get('city'),))
                values['counties'] = cr.dictfetchall()
                values['counties'] = values['counties']

            #如果微信电子卡券提货，需要微信电子卡券核销，也就是form需要提交到微信提货模块去处理
            if partner_id:
                values['form_action'] = '/card/exchange/new/%s' % partner_id
            else:
                values['form_action'] = '/card/exchange/new'
            if kw.get('card_id'):
                values['form_action'] = '/wx/card/exchange'
                #进行激活操作
                product_card_obj = registry.get('product.card.line')
                # 找到对应的卡券IDS
                card_ids = product_card_obj.search(cr, SUPERUSER_ID, [('code', 'in', [card_code])])
                if card_ids:
                    card = product_card_obj.browse(cr, SUPERUSER_ID, card_ids[0])
                    if not card.is_active:
                        # 激活卡券
                        product_card_obj = registry.get('product.card.line')
                        try:
                            product_card_obj.do_active(cr, SUPERUSER_ID, card_ids)
                        except openerp.exceptions.except_orm as e:
                            cr.rollback()
                            _logger.error(u'微信电子卡券激活失败: %s' % e[1])
                            #message.append(u'卡券无法激活，请联系客服4007285757')


            values.update({'partner': partner})
            #取得卡券对应的产品和是否多选一
            products_list = {}
            is_multiple_choice_one = sale_order['is_multiple_choice_one']
            values['is_multiple_choice_one'] = is_multiple_choice_one
            note = sale_order['note']
            if note:
                note = note.replace('\n', '<br />')
                values['note'] = note
            cr.execute('SELECT suite, pp.id, pp.name_template, socp.product_outer_name FROM sale_order_card_product socp' \
                       ' INNER JOIN product_product pp ON pp.id=socp.product_id' \
                       ' WHERE order_id=%s AND socp.is_enabled=TRUE', (so_id,))
            if is_multiple_choice_one:
                for product in cr.dictfetchall():
                    suite = product['suite']
                    product_name = product['product_outer_name'] if product['product_outer_name'] else product['name_template']
                    if products_list.has_key(suite):
                        products_list[suite] = products_list[suite] + ' ＋ ' + product_name
                    else:
                        products_list[suite] = product_name
            else:
                for product in cr.dictfetchall():
                    product_id = product['id']
                    products_list[product_id] = product['name_template']
        else:
            message.append(u'卡券不存在!')

        #values['debug'] = True
        #设置发日期默认值
        if not values.get('delivery_date'):
            values['delivery_date'] = start_delivery_date.strftime('%Y-%m-%d')
        values['message'] = "<br/>".join(message)
        values['card'] = card
        values['products_list'] = products_list
        values['provinces'] = provinces_sorted
        values['start_delivery_date'] = start_delivery_date.strftime('%Y-%m-%d')
        values['end_delivery_date'] = config_end_delivery_date.strftime('%Y-%m-%d')
        return http.request.website.render('dftg_weixin.new', values)
        # template = env.get_template("card/new.html")
        # return template.render(values)

    #快递查询接口
    def _query_express(self, com, code):
        data = {'key': '1edafec0dbd9469abc3a5b34a1f737bc', 'com': com, 'no': code}
        params = urllib.urlencode(data)
        json_string = u'{}'

        headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
        try:
            http_client = httplib.HTTPConnection("apis.haoservice.com", timeout=60)
            http_client.request("POST", "/lifeservice/exp", params, headers)

            response = http_client.getresponse()
            if response.status == 200:
                json_string = response.read()
        finally:
            if http_client:
                http_client.close()

        return json_string

    @http.route('/card/exchange/express-delivery-detail', auth='public', website=True)
    def card_exchange_express_delivery_detail(self, shipping_type, shipping_code):
        json_string = self._query_express(shipping_type, shipping_code)
        json_data = simplejson.loads(json_string)
        #如果正确，则返回快递详细信息
        if json_data.get('error_code') == 0:
            express_result = json_data.get('result')
            if express_result:
                result_list = express_result.get('data')
                result_html = ''
                if result_list:
                    for line in result_list:
                        result_html += line.get('time') + '<br />' + line.get('context') + '<br />\n'
                else:
                    result_html = u'无法查询'
                return result_html
        #如果有错误，则返回错误信息
        else:
            return json_data.get('reason')
        #return json_string

    @http.route(['/card/exchange/info',
                 '/card/exchange/info/<int:partner_id>'], auth='public', website=True)
    def card_exchange_info(self, partner_id=False, **kw):
        cr, uid, context = http.request.cr, http.request.uid, http.request.context
        card_code = kw.get('card_code')
        need_check_openid = False
        if card_code:
            openid = http.request.session.openid
            need_check_openid = True
            #检查传入的卡券号码是否合法
        else:
            card_code = request.session.card_code
        cr.execute('SELECT * FROM product_card_line WHERE code=%s', (card_code,))
        card = cr.dictfetchone()
        exchange = {}
        if card and card['is_exchanged']:
            if need_check_openid:
                cr.execute("SELECT * FROM apply_delivery WHERE code=%s AND openid=%s", (card['id'], openid))
            else:
                cr.execute("SELECT * FROM apply_delivery WHERE code=%s", (card['id'],))
            exchange = cr.dictfetchone()
            if exchange:
                exchange['province_name'] = ''
                exchange['city_name'] = ''
                exchange['county_name'] = ''
                #取得卡券提货订单行产品名称
                if exchange['so_id']:
                    cr.execute("""SELECT pp.id, sol.id as sol_id,
                    pp.name_template as product_name, sol.product_uom_qty as product_qty, socp.product_outer_name
                    FROM sale_order_line sol
                    INNER JOIN product_product pp ON pp.id=sol.product_id
                    INNER JOIN sale_order so ON so.id=sol.order_id
                    INNER JOIN apply_delivery ad ON ad.so_id=sol.order_id
                    INNER JOIN sale_order_card_product socp ON socp.order_id=so.card_so_id AND socp.product_id=sol.product_id
                    WHERE sol.order_id=%s and ad.suite=socp.suite""", (exchange['so_id'],))
                    products_list = cr.dictfetchall()
                    for product_item in products_list:
                        if product_item.get('product_outer_name'):
                            product_item.update({'product_name': product_item.get('product_outer_name')})
                #     cr.execute('SELECT name_template FROM product_product WHERE id=%s', (exchange['choice_product_id'],))
                #     product_name = cr.dictfetchone()['name_template']
                #     exchange['product_name'] = product_name
                # else:
                #     so_id = card['so_id']
                #     #取得卡券对应的产品和是否多选一
                #     cr.execute("SELECT is_multiple_choice_one FROM sale_order WHERE id=%s", (so_id,))
                #     exchange['is_multiple_choice_one'] = cr.dictfetchone()['is_multiple_choice_one']
                #     cr.execute('SELECT pp.id, pp.name_template FROM sale_order_card_product socp' \
                #        ' INNER JOIN product_product pp ON pp.id=socp.product_id' \
                #        ' WHERE order_id=%s', (so_id,))
                #     products_list = {}
                #     for product in cr.dictfetchall():
                #         products_list[product['id']] = product['name_template']
                    exchange['products_list'] = products_list
                #取得省市县名称
                if exchange.get('province_id'):
                    cr.execute('SELECT name FROM res_country_state WHERE id=%s', (exchange['province_id'],))
                    exchange['province_name'] = cr.dictfetchone()['name']
                if exchange.get('city_id'):
                    cr.execute('SELECT city_name FROM all_city WHERE id=%s', (exchange['city_id'],))
                    exchange['city_name'] = cr.dictfetchone()['city_name']
                if exchange.get('county_id'):
                    cr.execute('SELECT county_name FROM all_county WHERE id=%s', (exchange['county_id'],))
                    exchange['county_name'] = cr.dictfetchone()['county_name']
                #如果有货运类型
                if exchange['shipping_type']:
                    cr.execute("SELECT name, description FROM express_type WHERE id=%s", (exchange['shipping_type'],))
                    express_type = cr.dictfetchone()
                    if express_type:
                        exchange['express_type_name'] = express_type['name']
                        exchange['express_type_com'] = express_type['description']
                        #if express_type_code and shipping_code:
                            #调用查询快递接口
                            #self._query_express(express_type_code, shipping_code)
                cr.execute("SELECT is_stock_reserved FROM sale_order WHERE id=%s", (exchange['so_id'],))
                exchange_sale_order_row = cr.dictfetchone()
                exchange['is_stock_reserved'] = False
                if exchange_sale_order_row:
                    exchange['is_stock_reserved'] = exchange_sale_order_row.get('is_stock_reserved')
        partner = False
        if partner_id:
            partner = request.registry.get('res.partner').browse(cr, SUPERUSER_ID, partner_id, context=context)
        return http.request.website.render('dftg_weixin.info', {
            'card': card,
            'partner': partner,
            'exchange': exchange,
            'exchange_ok': kw.get('exchange_ok')
        })

    @http.route('/validate_code', auth='public', website=True)
    def validate_code(self, **kw):
        if not http.request.session.validate_code:
            time.sleep(5)
        else:
            time.sleep(1)
        code_img, code = create_validate_code()
        http.request.session.validate_code = code
        output = StringIO.StringIO()
        code_img.save(output, 'gif')
        img_data = output.getvalue()
        output.close()
        return request.make_response(img_data, headers=[('Content-Type', 'image/gif')])

    @http.route('/card/exchange/get_cities', auth='public', website=True, type="json")
    def get_cities(self, province_id):
        cr, uid, context = http.request.cr, http.request.uid, http.request.context

        cr.execute('SELECT id, city_name as name FROM all_city '\
                   'WHERE province_id=%s', (province_id,))
        cities = cr.dictfetchall()

        cities_sorted = cities

        return cities_sorted

    @http.route('/card/exchange/get_counties', auth='public', website=True, type="json")
    def get_counties(self, city_id):
        cr, uid, context = http.request.cr, http.request.uid, http.request.context

        cr.execute('SELECT id, county_name as name FROM all_county '\
                   'WHERE city_id=%s', (city_id,))
        counties = cr.dictfetchall()

        counties_sorted = counties

        return counties_sorted

    #查询卡券提货信息
    @http.route('/temp/card/<code>', auth='user', website=True)
    def card_info(self, code):
        cr, uid, context = http.request.cr, http.request.uid, http.request.context
        card_code = code
        cr.execute('SELECT * FROM product_card_line WHERE code=%s', (card_code,))
        card = cr.dictfetchone()
        exchange = {}
        if card and card['is_exchanged']:
            cr.execute("SELECT * FROM apply_delivery WHERE code=%s", (card['id'],))
            exchange = cr.dictfetchone()
            if exchange:
                exchange['province_name'] = ''
                exchange['city_name'] = ''
                exchange['county_name'] = ''
                #取得产品名称
                cr.execute('SELECT name_template FROM product_product WHERE id=%s', (card['product_id'],))
                product_name = cr.dictfetchone()['name_template']
                exchange['product_name'] = product_name
                #取得省市县名称
                if exchange.get('province'):
                    cr.execute('SELECT name FROM res_country_state WHERE id=%s', (exchange['province'],))
                    exchange['province_name'] = cr.dictfetchone()['name']
                if exchange.get('city'):
                    cr.execute('SELECT city_name FROM all_city WHERE id=%s', (exchange['city'],))
                    exchange['city_name'] = cr.dictfetchone()['city_name']
                if exchange.get('county'):
                    cr.execute('SELECT county_name FROM all_county WHERE id=%s', (exchange['county'],))
                    exchange['county_name'] = cr.dictfetchone()['county_name']
                #如果有货运类型
                if exchange['shipping_type']:
                    cr.execute("SELECT name, description FROM express_type WHERE id=%s", (exchange['shipping_type'],))
                    express_type = cr.dictfetchone()
                    if express_type:
                        exchange['express_type_name'] = express_type['name']
                        exchange['express_type_com'] = express_type['description']
                        #if express_type_code and shipping_code:
                            #调用查询快递接口
                            #self._query_express(express_type_code, shipping_code)

        return http.request.website.render('dftg_weixin.info', {
            'card': card,
            'exchange': exchange,
        })


    @http.route([
        '/website/dftg_ext/image',
        '/website/dftg_ext/image/<model>/<id>/<field>',
        '/website/dftg_ext/image/<model>/<id>/<field>/<int:max_width>x<int:max_height>'
    ], auth="public", website=True, multilang=False)
    def website_image_partner(self, model, id, field, max_width=None, max_height=None):
        """ Fetches the requested field and ensures it does not go above
        (max_width, max_height), resizing it if necessary.

        If the record is not found or does not have the requested field,
        returns a placeholder image via :meth:`~.placeholder`.

        Sets and checks conditional response parameters:
        * :mailheader:`ETag` is always set (and checked)
        * :mailheader:`Last-Modified is set iif the record has a concurrency
          field (``__last_update``)

        The requested field is assumed to be base64-encoded image data in
        all cases.
        """
        try:
            idsha = id.split('_')
            id = idsha[0]
            response = werkzeug.wrappers.Response()
            user_id = SUPERUSER_ID
            return request.registry['website']._image(
                request.cr, user_id, model, id, field, response, max_width, max_height,
                cache=STATIC_CACHE if len(idsha) > 1 else None)
        except Exception:
            logger.exception("Cannot render image field %r of record %s[%s] at size(%s,%s)",
                             field, model, id, max_width, max_height)
            response = werkzeug.wrappers.Response()
            return self.placeholder(response)